package drds.plus.repository.mysql.handler;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.command_handler.CommonCommandHandler;
import drds.plus.executor.command_handler.TableWithIndexMetaData;
import drds.plus.executor.cursor.cursor.ISortingCursor;
import drds.plus.executor.record_codec.record.Record;
import drds.plus.executor.repository.IDatasourceManagerGetter;
import drds.plus.executor.row_values.RowValues;
import drds.plus.executor.table.ITable;
import drds.plus.executor.transaction.Transaction;
import drds.plus.repository.mysql.spi.DatasourceManagerGetterImpl;
import drds.plus.repository.mysql.spi.JdbcHandler;
import drds.plus.repository.mysql.spi.RepositoryImpl;
import drds.plus.sql_process.abstract_syntax_tree.configuration.IndexMapping;
import drds.plus.sql_process.abstract_syntax_tree.execute_plan.ExecutePlan;
import drds.plus.sql_process.abstract_syntax_tree.execute_plan.dml.IPut;
import drds.plus.sql_process.abstract_syntax_tree.execute_plan.dml.PutType;

public abstract class PutMyHandlerCommon extends CommonCommandHandler {

    protected IDatasourceManagerGetter dataSourceGetter;

    public PutMyHandlerCommon() {
        super();
        dataSourceGetter = new DatasourceManagerGetterImpl();
    }

    public ISortingCursor handle(ExecuteContext executeContext, ExecutePlan executePlan) throws RuntimeException {
        IPut put = (IPut) executePlan;
        JdbcHandler jdbcHandler = ((RepositoryImpl) executeContext.getRepository()).getJdbcHandler(executeContext, executePlan, dataSourceGetter);
        TableWithIndexMetaData tableWithIndexMetaData = new TableWithIndexMetaData();

        prepareTableAndIndexMetaDataForPut(executeContext, put, tableWithIndexMetaData);
        ITable table = tableWithIndexMetaData.table;
        IndexMapping indexMapping = tableWithIndexMetaData.indexMapping;

        ISortingCursor result = null;
        try {
            result = executePut(executeContext, put, table, indexMapping, jdbcHandler);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;

    }

    protected abstract ISortingCursor executePut(ExecuteContext executeContext, IPut put, ITable table, IndexMapping meta, JdbcHandler myJdbcHandler) throws Exception;

    protected void prepare(Transaction transaction, ITable table, RowValues oldkv, Record key, Record value, PutType putType) throws RuntimeException {
    }

}
